package com.explorer.ider.bootguide;

import android.annotation.TargetApi;
import android.app.Instrumentation;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.explorer.ider.bootguide.adapter.MyPagerAdapter;
import com.explorer.ider.bootguide.fragment.FragmentAppSelect;
import com.explorer.ider.bootguide.fragment.FragmentLanguage;
import com.explorer.ider.bootguide.fragment.FragmentNet;
import com.explorer.ider.bootguide.fragment.FragmentNets;
import com.explorer.ider.bootguide.fragment.FragmentScreenPosition;
import com.explorer.ider.bootguide.fragment.FragmentWelcome;
import com.explorer.ider.bootguide.fragment.FragmentZaiDian1;
import com.explorer.ider.bootguide.fragment.FragmentZaiDian2;
import com.explorer.ider.bootguide.fragment.FragmentZaiDian3;
import com.explorer.ider.bootguide.fragment.FragmentZaiDian4;
import com.explorer.ider.bootguide.fragment.FragmentZaiDian5;
import com.explorer.ider.bootguide.utils.HomeWatcherReceiver;
import com.explorer.ider.bootguide.utils.NetUtil;

import java.util.ArrayList;
import java.util.List;

public class MainActivitys extends AppCompatActivity{

    private static final  String TAG = "MainActivity";
    //ViewPager and Fragment
    private ViewPager mBootGuideViewPager;
    private MyPagerAdapter mBootGuidePagerAdapter;
    private List<Fragment> mAllFragment;
    public static final String ACTION_TO_NEXT_PAGER1 = "ACTION_TO_NEXT_PAGER1" ;
    public static final String ACTION_TO_NEXT_PAGER2 = "ACTION_TO_NEXT_PAGER2" ;
    public static final String ACTION_TO_NEXT_PAGER3 = "ACTION_TO_NEXT_PAGER3" ;
    public static final String ACTION_TO_NEXT_PAGER4 = "ACTION_TO_NEXT_PAGER4" ;
    public static final String ACTION_TO_NEXT_PAGER5 = "ACTION_TO_NEXT_PAGER5" ;
    public static final String ACTION_TO_NEXT_PAGER6 = "ACTION_TO_NEXT_PAGER6" ;
    public static final String ACTION_TO_NEXT_PAGER7 = "ACTION_TO_NEXT_PAGER7" ;
    public static final String ACTION_TO_NEXT_PAGER8 = "ACTION_TO_NEXT_PAGER8" ;
    public static final String ACTION_TO_NEXT_PAGER9 = "ACTION_TO_NEXT_PAGER9" ;
    public static final String ACTION_TO_NEXT_PAGER10 = "ACTION_TO_NEXT_PAGER10";
    public static final String ACTION_TO_NEXT_PAGER11 = "ACTION_TO_NEXT_PAGER11";
    public static final String ACTION_TO_BACK_PAGER1 = "ACTION_TO_BACK_PAGER1" ;
    public static final String ACTION_TO_BACK_PAGER2 = "ACTION_TO_BACK_PAGER2" ;
    public static final String ACTION_TO_BACK_PAGER3 = "ACTION_TO_BACK_PAGER3" ;
    public static final String ACTION_TO_BACK_PAGER4 = "ACTION_TO_BACK_PAGER4" ;
    public static final String ACTION_TO_BACK_PAGER5 = "ACTION_TO_BACK_PAGER5" ;
    public static final String ACTION_TO_FINISH = "ACTION_TO_FINISH " ;
    public static final String ACTION_SCREEN_NARROW = "Action_screen_narrow";
    public static final String ACTION_SCREEN_ENLARGE = "Action_screen_enlarge";
    private static HomeWatcherReceiver mHomeKeyReceiver = null;

    private boolean languageSettingOk = false;//设置语言后，会重新执行onCreate方法，使用这个参数让他直接跳转至第二页
    public static final String DEVICE_NAME = Build.DEVICE;
    private  final int WIFI_SCAN_PERMISSION_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }else {
            View decorView = getWindow().getDecorView();
            // Hide both the navigation bar and the status bar.
            // SYSTEM_UI_FLAG_FULLSCREEN is only available on Android 4.1 and higher, but as
            // a general rule, you should design your app to hide the status bar whenever you
            // hide the navigation bar.
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
        setContentView(R.layout.activity_main);
        initPermission();
        initData();
        initViews();
        registerHomeKeyReceiver(this);
        Log.i(TAG, "onCreate: " + DEVICE_NAME);
    }

    private void initPermission(){
//        if (ContextCompat.checkSelfPermission(this,Manifest.permission_group.LOCATION)!=PackageManager.PERMISSION_GRANTED){
            // 获取wifi连接需要定位权限,没有获取权限
            ActivityCompat.requestPermissions(this,new String[]{
                    Manifest.permission.ACCESS_WIFI_STATE,
            },WIFI_SCAN_PERMISSION_CODE);
            return;
//        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case WIFI_SCAN_PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 允许
                    initData();

                } else {
                    // 不允许
//                    Toast.makeText(this, getString(R.string.permisstion_deny), Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
        //unregisterHomeKeyReceiver(this);
    }

    private void initData(){
        mAllFragment = new ArrayList<>();

        mAllFragment.add(new FragmentLanguage());
        mAllFragment.add(new FragmentNet());
        mAllFragment.add(new FragmentNets());
        //mAllFragment.add(new FragmentDateTime());
        mAllFragment.add(new FragmentScreenPosition());
//        mAllFragment.add(new FragmentTwoDimen());
        //mAllFragment.add(new FragmentGoogleLogin());
        mAllFragment.add(new FragmentAppSelect());
        mAllFragment.add(new FragmentZaiDian1());
        mAllFragment.add(new FragmentZaiDian2());
        mAllFragment.add(new FragmentZaiDian3());
        mAllFragment.add(new FragmentZaiDian4());
        mAllFragment.add(new FragmentZaiDian5());
        mAllFragment.add(new FragmentWelcome());
        IntentFilter mToNextIntentFilter = new IntentFilter();
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER1);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER2);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER3);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER4);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER5);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER6);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER7);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER8);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER9);
        mToNextIntentFilter.addAction(ACTION_TO_NEXT_PAGER10);
        mToNextIntentFilter.addAction(ACTION_TO_BACK_PAGER1);
        mToNextIntentFilter.addAction(ACTION_TO_BACK_PAGER2);
        mToNextIntentFilter.addAction(ACTION_TO_BACK_PAGER3);
        mToNextIntentFilter.addAction(ACTION_TO_BACK_PAGER4);
        mToNextIntentFilter.addAction(ACTION_TO_BACK_PAGER5);


        mToNextIntentFilter.addAction(ACTION_TO_FINISH);
        registerReceiver(mToNextReceiver,mToNextIntentFilter);
//        AnimationSet animationSet = new AnimationSet(true);
//        ObjectAnimator oj = new ObjectAnimator();
//        oj.setPropertyName("alpha");
//        oj.setFloatValues(0.5f,0.2f);
//        oj.addUpdateListener();
//        PropertyValuesHolder pvr = PropertyValuesHolder.ofFloat();
//        ObjectAnimator.ofPropertyValuesHolder(pvr,pvr,pvr);
//        AnimationSet set = new AnimationSet();
//        ActivityOptionsCompat.
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode){
            case KeyEvent.KEYCODE_BACK:
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initViews() {
        mBootGuideViewPager = (ViewPager) findViewById(R.id.id_main_viewpager);
        mBootGuidePagerAdapter = new MyPagerAdapter(getSupportFragmentManager(),mAllFragment);
        mBootGuideViewPager.setAdapter(mBootGuidePagerAdapter);
        if (languageSettingOk){
            if (NetUtil.isNetworkAvailable(this)){
                mBootGuideViewPager.setCurrentItem(2);
            }else {
                mBootGuideViewPager.setCurrentItem(1);

            }
        }
    }


    public void toNextPager(int whatCard){
        mBootGuideViewPager.setCurrentItem(whatCard);
    }


    BroadcastReceiver mToNextReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER1)){
                mBootGuideViewPager.setCurrentItem(1);
                Log.i("tag","1");
            }else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER2)){
                mBootGuideViewPager.setCurrentItem(2);
                Log.i("tag","2");
            }else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER3)) {
                mBootGuideViewPager.setCurrentItem(3);
                Log.i("tag","3");
            }else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER4)){
                mBootGuideViewPager.setCurrentItem(4);
                Log.i("tag","4");
            } else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER5)){
                mBootGuideViewPager.setCurrentItem(5);
                Log.i("tag","5");
            } else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER6)){
                mBootGuideViewPager.setCurrentItem(6);
                Log.i("tag","6");
            } else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER7)){
                mBootGuideViewPager.setCurrentItem(7);
                Log.i("tag","7");
            } else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER8)){
                mBootGuideViewPager.setCurrentItem(8);
                Log.i("tag","8");
            } else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER9)){
                mBootGuideViewPager.setCurrentItem(9);
                Log.i("tag","9");
            } else
            if(intent.getAction().equals(ACTION_TO_NEXT_PAGER10)){
                mBootGuideViewPager.setCurrentItem(10);
                Log.i("tag","10");
            } else
            if(intent.getAction().equals(ACTION_TO_BACK_PAGER1)){
                mBootGuideViewPager.setCurrentItem(0);
            }else
            if(intent.getAction().equals(ACTION_TO_BACK_PAGER2)){
                mBootGuideViewPager.setCurrentItem(0);
            }else
            if(intent.getAction().equals(ACTION_TO_BACK_PAGER3)) {
                mBootGuideViewPager.setCurrentItem(1);
            }else
            if(intent.getAction().equals(ACTION_TO_BACK_PAGER4)){
                mBootGuideViewPager.setCurrentItem(1);
            } else
            if(intent.getAction().equals(ACTION_TO_BACK_PAGER5)){
                mBootGuideViewPager.setCurrentItem(3);
            }else
            if(intent.getAction().equals(ACTION_TO_FINISH)){
                finishSetupWizard();
//                Toast.makeText(context,"结束",Toast.LENGTH_LONG).show();
//                finish();
            }

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mToNextReceiver);
        unregisterHomeKeyReceiver();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void finishSetupWizard() {
        // Add a persistent setting to allow other apps to know the device has been provisioned.
        Settings.Global.putInt(getContentResolver(), Settings.Global.DEVICE_PROVISIONED , 1);

        // remove this activity from the package manager.
        /*
        不可用状态：COMPONENT_ENABLED_STATE_DISABLED
        可用状态：COMPONENT_ENABLED_STATE_ENABLED
        默认状态：COMPONENT_ENABLED_STATE_DEFAULT
         */
        PackageManager pm = getPackageManager();
        ComponentName name = new ComponentName(this, MainActivity.class);
        pm. setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED ,PackageManager.DONT_KILL_APP );
        finish();
    }

    public static void sendKeyCode(final int keyCode){
        new Thread () {
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    inst.sendKeyDownUpSync(keyCode);
                } catch (Exception e) {
                    Log.e(TAG,e.toString());
                }
            }
        }.start();
    }

    private static void registerHomeKeyReceiver(Context context) {
        Log.i(TAG, "registerHomeKeyReceiver");
        mHomeKeyReceiver = new HomeWatcherReceiver();
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        context.registerReceiver(mHomeKeyReceiver, homeFilter);
    }


    private  void unregisterHomeKeyReceiver() {
        Log.i(TAG, "unregisterHomeKeyReceiver");

        unregisterReceiver(mHomeKeyReceiver);


    }

}
